package com.dkd.day20250619;

import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;

public class SolutionGetLeastNumbers_Solution {
    public static void main(String[] args) {

    }

    public ArrayList<Integer> GetLeastNumbers_Solution (int[] input, int k) {
        // write code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (input == null || k <= 0 || k > input.length) {
            return result; // 边界条件处理
        }
        PriorityQueue<Integer> maxheap = new PriorityQueue<Integer>(k,
                Collections.reverseOrder());
        for (int num : input) {
            if (maxheap.size() < k) {
                maxheap.offer(num); // 堆未满，直接插入
            } else if (num < maxheap.peek()) {
                maxheap.poll();     // 弹出当前最大值
                maxheap.offer(num); // 插入更小的值
            }
        }

        // 将堆中的元素转为升序排列
        while (!maxheap.isEmpty()) {
            result.add(maxheap.poll());
        }


        return result;
    }
}
